package com.example.hostsys.controller;

import com.example.hostsys.dao.HouseDao;
import com.example.hostsys.dao.MeetDao;
import com.example.hostsys.dao.StuDao;
import com.example.hostsys.entity.House;
import com.example.hostsys.entity.Meeting;
import com.example.hostsys.entity.Student;
import com.example.hostsys.entity.User;
import com.example.hostsys.payloads.AddMeetPay;
import com.example.hostsys.service.UserService;
import com.example.hostsys.util.ResultSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/stu")
public class StuController {
    private String pre = "student";
    final UserService userService;

    @Autowired
    HouseDao houseDao;
    @Autowired
    MeetDao meetDao;
    @Autowired
    StuDao stuDao;

    @Autowired
    public StuController(UserService userService){this.userService=userService;}

    @GetMapping("/home")
    public String home(){
        return pre + "/home";
    }
    @GetMapping("/gethouse")
    @ResponseBody
    public ResultSet getHouse(){
        List<House> houses=houseDao.findAll();
        for(House house:houses){
            house.sortPics();
        }
        return ResultSet.build(houses);
    }

    @PostMapping("/addMeet")
    @ResponseBody
    public ResultSet addMeet(@RequestBody AddMeetPay addMeetPay, Authentication auth){
        System.out.println(addMeetPay.getDatetime());
        Optional<House> o=houseDao.findById(addMeetPay.getHouseID());
        if(!o.isPresent()){
            return ResultSet.fail();
        }
        House house=o.get();
        Student student= userService.findUser(auth.getName()).getStu();
        Meeting meeting=new Meeting(house,student,addMeetPay);
        meetDao.save(meeting);
        return ResultSet.success();
    }
    @PostMapping("/getMeet")
    @ResponseBody
    public ResultSet getMeet(Authentication auth){
        User user=userService.findUser(auth.getName());
        Student student=stuDao.findByUser(user);
        List<Meeting> meetings=meetDao.findAllByStudentOrderByUpdateTimeDesc(student);
        return ResultSet.build(meetings);
    }
}
